/**
Defines the main function for the daytime client.
*/
#include "globals.h"

int global_pfd;
void sig_term(int signum);

/**
The main function.
*/
int 
main(
    int argc,
    char *argv[]
    )
{
    int sockfd;
    struct sockaddr_in serv_addr;
    int pfd;
    char bufr[MAXLINE];
    int n;
        
    //
    // Create the socket and connect to the server.
    //

    sockfd = Socket(AF_INET, SOCK_STREAM, 0);

    bzero(&serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT_NUM_TIME); 
    
    Inet_pton(AF_INET, argv[1], &serv_addr.sin_addr);

    if (connect(sockfd, (SA *) &serv_addr, sizeof(serv_addr)) < 0)
    {
        Write(pfd, DIAG_TIME_CLIENT_CONN_ERR,\ 
            strlen(DIAG_TIME_CLIENT_CONN_ERR));

        err_sys("socket error");
    }
    
    pfd = atoi(argv[2]);
    global_pfd = pfd;

    //
    // Connection established.
    //

    Write(pfd, DIAG_TIME_CLIENT_CONN, strlen(DIAG_TIME_CLIENT_CONN));

    //
    // Signal handler for termination.
    //

    Signal(SIGABRT, sig_term);
    Signal(SIGTERM, sig_term);

    //
    // Time client only reads data. It is an error if this while loop 
    // terminates as server is expected to write data indefinitely.
    //

    while((n = Readline(sockfd, bufr, MAXLINE)) > 0)
    {
        bufr[n] = 0;
        Write(fileno(stdout), bufr, n+1);
    }

    Write(pfd, SRV_PREMATURE_TERM, strlen(SRV_PREMATURE_TERM));
     
    return 0;
}

/**
Signal handler.
*/
void 
sig_term(
    int signum
    )
{
    //
    // Terminating client. Write this message to the pipe.
    //

    Write(global_pfd, DIAG_TIME_CLIENT_TERM, strlen(DIAG_TIME_CLIENT_TERM));
}

